package com.muyonghui.myjavaweb.controller;

import com.muyonghui.myjavaweb.db.DBConnection;
import com.muyonghui.myjavaweb.db.entities.UserEntity;
import com.muyonghui.myjavaweb.model.ValidUserBean;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import javax.xml.ws.RequestWrapper;
import java.util.List;

/**
 * Created by muyonghui on 2017/4/13.
 */
@Controller
public class UserCtrl {

    @Autowired
    ValidUserBean validUserBean;

    @RequestMapping(value = "users", method = RequestMethod.GET)
    public String listUsers(ModelMap map){

        Session session = DBConnection.getSession();
        List<UserEntity> list = session.createCriteria(UserEntity.class).list();
        map.addAttribute("users",list);


        session.close();
        return "users";
    }

    @RequestMapping(value = "adduser", method = RequestMethod.GET)
    public String addUser(Model map){
        map.addAttribute("validUserBean", validUserBean);
        return "adduser";
    }

    @RequestMapping(value = "adduser", method = RequestMethod.POST)
    public String result(ModelMap map, @ModelAttribute("validUserBean") @Valid ValidUserBean validUserBean, BindingResult result ){

        if (result.hasErrors()){
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                map.addAttribute("ERR_" + fieldError.getField(), fieldError.getDefaultMessage());
            }
            return "adduser";
        }
        Session session = DBConnection.getSession();

        Transaction transaction = session.beginTransaction();

        UserEntity usr = new UserEntity();
        usr.setName(validUserBean.getName());
        usr.setAge(validUserBean.getAge());
        session.save(usr);
        transaction.commit();

        session.close();


        return "result";
    }
}
